package com.hmdp.utils;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;

import java.util.concurrent.TimeUnit;

public class RedisLock {
    StringRedisTemplate stringRedisTemplate;
    public RedisLock(StringRedisTemplate stringRedisTemplate){
        this.stringRedisTemplate=stringRedisTemplate;
    }
    public boolean tryLock(String key,long expireSeconds) {
        //获取当前线程
        long threadId = Thread.currentThread().getId();
        Boolean flag = stringRedisTemplate.opsForValue().setIfAbsent(key, String.valueOf(threadId), expireSeconds, TimeUnit.SECONDS);
        return Boolean.TRUE.equals(flag);
    }

    public void unLock(String key) {
        stringRedisTemplate.delete(key);
    }
}
